var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "path", "koa-router", "../com/DBTool/DBTool", "../com/configTool", "../lib/FSTool/index", "../com/DBTool/DBConnectTool", "../lib/GISServer/CesiumTerrain/CesiumTerrain", "../lib/GISServer/MapboxTile/MapboxTile", "../lib/FSTool/EncryptFiles/threadEncryptFiles/index", "../com/webSocketTool/webSocketTool", "../lib/FSTool/getFilePathList"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const path_1 = __importDefault(require("path"));
    const koa_router_1 = __importDefault(require("koa-router"));
    const DBTool_1 = __importDefault(require("../com/DBTool/DBTool"));
    const configTool_1 = __importDefault(require("../com/configTool"));
    const index_1 = __importDefault(require("../lib/FSTool/index"));
    const DBConnectTool_1 = __importDefault(require("../com/DBTool/DBConnectTool"));
    const CesiumTerrain_1 = __importDefault(require("../lib/GISServer/CesiumTerrain/CesiumTerrain"));
    const MapboxTile_1 = __importDefault(require("../lib/GISServer/MapboxTile/MapboxTile"));
    const index_2 = __importDefault(require("../lib/FSTool/EncryptFiles/threadEncryptFiles/index"));
    const webSocketTool_1 = __importDefault(require("../com/webSocketTool/webSocketTool"));
    const getFilePathList_1 = __importDefault(require("../lib/FSTool/getFilePathList"));
    const ManageRoutes = new koa_router_1.default({ prefix: '/manage' });
    ManageRoutes
        .get('/getDBInfoList', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let fileInfoList = await DBTool_1.default.getDBInfoList() || [];
        ctx.body = JSON.stringify(fileInfoList);
    })
        .get('/getDBPathTree', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName } = ctx.request.query;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        let res = await dbTool.getDBPathTree();
        ctx.body = JSON.stringify(res);
    })
        .get('/getFileListByPath', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, path } = ctx.request.query;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        let res = await dbTool.getDirListByPath(path);
        ctx.body = JSON.stringify(res);
    })
        .get('/getDirInfo', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, dirPath } = ctx.request.query;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        let res = await dbTool.getDirInfo(dirPath);
        ctx.body = JSON.stringify(res);
    })
        .get('/createDB', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, targetDirectory, mataData } = ctx.request.query;
        if (mataData) {
            mataData = JSON.parse(mataData);
        }
        let msg = await DBTool_1.default.createDB(DBName, targetDirectory, mataData);
        ctx.body = JSON.stringify({ msg });
    })
        .get('/appendFile', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, targetDirectory, currentDirectory } = ctx.request.query;
        let msg = await DBTool_1.default.appendFile(DBName, targetDirectory, currentDirectory);
        await DBConnectTool_1.default.reConnect(DBName);
        ctx.body = JSON.stringify({ msg });
    })
        .get('/clearFileDate', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName } = ctx.request.query;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        await DBConnectTool_1.default.reConnect(DBName);
        let res = await dbTool.clearFileDate();
        ctx.body = JSON.stringify(res);
    })
        .get('/wipeCache', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName } = ctx.request.query;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        await DBConnectTool_1.default.reConnect(DBName);
        let res = await dbTool.wipeCache();
        ctx.body = JSON.stringify(res);
    })
        .get('/deleteByFullPath', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, fullPath } = ctx.request.query;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        await DBConnectTool_1.default.reConnect(DBName);
        let res = await dbTool.deleteByFullPath(fullPath);
        ctx.body = JSON.stringify(res);
    })
        .get('/deleteByDir', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, directory } = ctx.request.query;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        await DBConnectTool_1.default.reConnect(DBName);
        let res = await dbTool.deleteByDir(directory);
        ctx.body = JSON.stringify(res);
    })
        .get('/exportDB', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, targetDirectory } = ctx.request.query;
        let res = await DBTool_1.default.exportDB(DBName, targetDirectory);
        ctx.body = JSON.stringify({ res });
    })
        .get('/deleteDB', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName } = ctx.request.query;
        if (DBName) {
            await DBConnectTool_1.default.closeAll();
            let result = await DBTool_1.default.deleteDB(DBName);
            ctx.body = JSON.stringify({ result });
        }
        else {
            ctx.status = 404;
        }
    })
        .get('/getFileBySearch', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, text } = ctx.request.query;
        if (DBName && text) {
            let dbTool = await DBConnectTool_1.default.openDB(DBName);
            let list = await dbTool.getFileListBySearch(text);
            list.map((item) => item.ext = path_1.default.extname(item.file_name));
            ctx.body = JSON.stringify(list);
        }
        else {
            ctx.status = 404;
        }
    })
        .get('/threadEncryptFiles', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { inputPath, outPutPath, passWorld, threadNum } = ctx.request.query;
        if (inputPath && outPutPath && passWorld && threadNum) {
            const filePathList = await (0, getFilePathList_1.default)(inputPath);
            const beginTime = new Date().getTime();
            const mes = await (0, index_2.default)(filePathList, inputPath, outPutPath, passWorld, (e) => {
                e.action = 'runProgress';
                e.passTime = Math.ceil((new Date().getTime() - beginTime) / 1000);
                webSocketTool_1.default.send(JSON.stringify(e));
            }, threadNum);
            ctx.body = JSON.stringify(mes);
        }
        else {
            ctx.status = 400;
            ctx.body = JSON.stringify({ msg: '参数错误' });
        }
    })
        .get('/getClientServerWebLog', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        const [err, text] = await index_1.default.readFileAsync(path_1.default.join(configTool_1.default.appBasePath, './temp/logs/clientServer/WebLog.json'));
        if (text) {
            ctx.body = JSON.parse(`[${text.toString().slice(0, -2)}]`);
        }
        else {
            ctx.body = [];
        }
    })
        .get('/getManageServerWebLog', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        const [err, text] = await index_1.default.readFileAsync(path_1.default.join(configTool_1.default.appBasePath, './temp/logs/manageServerPort/WebLog.json'));
        if (text) {
            ctx.body = JSON.parse(`[${text.toString().slice(0, -2)}]`);
        }
        else {
            ctx.body = [];
        }
    })
        .get('/getLogSummary', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        const [err0, text0] = await index_1.default.readFileAsync(path_1.default.join(configTool_1.default.appBasePath, './temp/logs/clientServer/WebLog.json'));
        const [err1, text1] = await index_1.default.readFileAsync(path_1.default.join(configTool_1.default.appBasePath, './temp/logs/manageServerPort/WebLog.json'));
        const logSummaryMap = new Map();
        if (text0 && text1) {
            const clientWebLog = JSON.parse(`[${text0.toString().slice(0, -2)}]`);
            const manageWebLog = JSON.parse(`[${text1.toString().slice(0, -2)}]`);
            clientWebLog.forEach((item) => {
                const ip = item.ip;
                const start = new Date(item.start).toDateString();
                const key = `${ip}-${start}`;
                if (logSummaryMap.has(key)) {
                    const value = logSummaryMap.get(key);
                    value.count++;
                }
                else {
                    const isoDate = new Date(start).toISOString().replace(/T.*/, '');
                    logSummaryMap.set(key, { ip, isoDate, count: 1 });
                }
            });
        }
        ctx.body = Array.from(logSummaryMap.values());
    })
        .post('/setMataData', async (ctx) => {
        ctx.set('Content-Type', 'application/json;charset=utf-8');
        let { DBName, mataData } = ctx.request.body;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        if (mataData) {
            mataData = JSON.parse(mataData);
        }
        let msg = await dbTool.setMataData(mataData);
        ctx.body = JSON.stringify({ msg });
    })
        .get('/api.mapbox.com/v4/mapbox.satellite/:z/:x/:y.webp', async (ctx) => {
        let { z, x, y } = ctx.params;
        let [err, buffer] = await MapboxTile_1.default.getSatelliteFileBuffer(z, x, y);
        if (buffer) {
            ctx.set('Content-Type', 'image/jpeg');
            ctx.body = buffer;
        }
        else {
            ctx.status = 422;
            ctx.set('Content-Type', 'application/json;charset=utf-8');
            ctx.body = err;
            console.log('代理 MapBoxTile 瓦片失败', z, x, y);
        }
    })
        .get('/api.mapbox.com/v4/mapbox.terrain-rgb/:z/:x/:y.png', async (ctx) => {
        let { z, x, y } = ctx.params;
        let [err, buffer] = await MapboxTile_1.default.getTerrainRGBFileBuffer(z, x, y);
        if (buffer) {
            ctx.set('Content-Type', 'image/png');
            ctx.body = buffer;
        }
        else {
            ctx.status = 422;
            ctx.set('Content-Type', 'application/json;charset=utf-8');
            ctx.body = err;
            console.log('代理 MapBoxTile 瓦片失败', z, x, y);
        }
    })
        .get('/assets.cesium.com/1/:url(.*)', async (ctx) => {
        const url = ctx.params.url;
        let fileSavePath = path_1.default.join(configTool_1.default.appBasePath, 'temp/fileOut/assets.cesium.com/1/', url);
        let [err, buffer] = await index_1.default.readFileAsync(fileSavePath);
        if (err) {
            [err, buffer] = await CesiumTerrain_1.default.getFileBuffer(url);
        }
        if (buffer) {
            ctx.body = buffer;
        }
        else {
            ctx.status = 422;
            ctx.body = err;
            console.log(`代理 Cesium 官方地形数据失败，${ctx.url}`);
        }
    });
    exports.default = ManageRoutes;
});
